import base64
import pickle

from django_redis import get_redis_connection


def merge_cart_cookie_to_redis(request, user, response):
    # 获取cookie
    cart_cookie = request.COOKIES.get('cart_cookie')
    # 判断cookie是否存在
    if cart_cookie is None:
        # 不存在返回
        return response
    # 解密cookie
    cart = pickle.loads(base64.b64decode(cart_cookie))
    # 判断解密后的值是否为空值
    if cart is None:
        # 为空返回
        return response
    # 数据拆分

    # 拆分为hash类型  字典保存
    data = {}
    # 拆分集合类型  列表形式保存
    data_list = []  # 保存选中状态的sku_id
    data_list_none = []  # 保存未选中状态的sku_id

    for sku_id, data_dict in cart.items():
        data[sku_id] = data_dict['count']
        if data_dict['selected']:
            data_list.append(sku_id)
        else:
            data_list_none.append(sku_id)
    # 建立redis链接对象
    conn = get_redis_connection('cart')
    conn.hmset('cart_%s' % user.id, data)
    # 写入hash类型
    if data_list:
        conn.sadd('cart_selected_%s' % user.id, *data_list)
    if data_list_none:
        conn.srem('cart_selected_%s' % user.id, *data_list_none)


        # 删除cookie
    response.delete_cookie('cart_cookie')

    return response